<?php
/**
 * Created by PhpStorm.
 * User: nightelf
 * Date: 2020/11/29
 * Time: 18:01
 */

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SupplierOrdersReturnedModel
{
    const TABLE = 'supplier_orders_returned';
    /**
     * @param array $data
     * @return bool|mixed
     */
    public function returned(array $data)
    {
        DB::beginTransaction();
        try {
            $totalPrice = 0;
            $warehouseModel = new WarehouseModel();
            $warehouseLogModel = new WarehouseLogModel();
            $warehouseLogInfoModel = new WarehouseLogInfoModel();
            $logId = $warehouseLogModel->insert([
                'projectId' => $data['projectId'],
                'price' =>$data['price'],
                'type' => $warehouseLogModel::RETURNED_PURCHASE,
                'sourceSupplierId' => $data['supplierId'],
                'time' => $data['returnedTime'],
                'createTime' => date('Y-m-d H:i:s'),
                'remark' => $data['remark'],
                'adminId' =>$data['adminId'],
            ]);
            foreach ($data['data'] as $key => $d) {
                $totalPrice += $d['totalPrice'];
                $supplierOrdersReturnedInfoData[] = [
                    'materialId' => $d['materialId'],
                    'specId' => $d['specId'],
                    'supplierId' => $data['supplierId'],
                    'amount' => $d['amount'],
                    'price' => $d['price'],
                    'totalPrice' => $d['totalPrice'],
                    'unitId' => $d['unitId'],
                ];
                //更新仓库库存
                $info = $warehouseModel->info(['projectId'=>$data['projectId'],'materialId'=>$d['materialId'],'specId'=>$d['specId']]);
                $newAmount = $info['amount']-$d['amount'];
                if($newAmount >0){
                    $newPurchasePrice = ($info['amount']*$info['purchasePrice']-$d['totalPrice'])/$newAmount;
                }else{
                    $newPurchasePrice = $info['purchasePrice'];
                }

                $warehouseModel->update(['id'=>$info['id']],['amount'=>$newAmount,'purchasePrice'=>$newPurchasePrice]);
                //更新出入库记录
                $warehouseLogInfoModel->insert([
                    'logId'=>$logId,
                    'materialId' => $d['materialId'],
                    'specId' => $d['specId'],
                    'amount' => $d['amount'],
                    'surplus' =>$newAmount,
                    'price' => $d['price'],
                    'totalPrice' => $d['totalPrice'],
                    'unitId' => $d['unitId'],
                ]);
            }
            //增加供应商退货记录
            $supplierOrderReturned = [
                'supplierId' => $data['supplierId'],
                'projectId' => $data['projectId'],
                'totalPrice' => $totalPrice,
                'returnedTime' => $data['returnedTime'],
                'payType' => $data['payType'],
                'createTime' => date('Y-m-d H:i:s'),
                'adminId' =>$data['adminId'],
            ];
            $supplierOrderReturnedId = $this->insert($supplierOrderReturned);
            $supplierOrdersReturnedInfoModel = new SupplierOrdersReturnedInfoModel();
            foreach ($supplierOrdersReturnedInfoData as $k => $soi) {
                $supplierOrdersReturnedInfoData[$k]['orderId'] = $supplierOrderReturnedId;
            }
            //更新
            if (!empty($supplierOrdersReturnedInfoData)) {
                $supplierOrdersReturnedInfoModel->insert($supplierOrdersReturnedInfoData);
            }
            DB::commit();
            return $supplierOrderReturnedId;
        } catch (\Exception $e) {
            Log::info($e->getMessage() . ' in ' . $e->getFile() . '(' . $e->getLine() . ')');
            DB::rollback();
            return false;
        }
    }

    public function insert(array $data)
    {
        return DB::table(self::TABLE)->insertGetId($data);
    }
}